<template>
    <div class="tab-bar-item" :class="{ active: isActive }" @click="handleClick">
      <i :class="iconStyle"></i>
      <slot></slot>
    </div>
  </template>
  
  <script setup>
    import { computed, inject, getCurrentInstance } from 'vue'
  
    const parent = inject('TabBar')
    const instance = getCurrentInstance()
  
    // 将当前实例注册到父组件的子组件列表中
    parent.link(instance)
    // 计算当前子组件中数组中的索引值
    const index = computed(() => {
      return parent.children.indexOf(instance)
    })
  
    const props = defineProps({
      icon: {
        type: String,
        required: true,
        default: 'user',
      },
    })
    // 判断传入的值和当前的索引值是否相等. 相等就加上active样式
    const isActive = computed(() => {
      return parent.props.modelValue === index.value
    })
  
    const iconStyle = computed(() => {
      return `iconfont icon-${props.icon}`
    })
  
    const handleClick = () => {
      parent.setActive(index.value)
    }
  </script>
  
  <style scoped>
    /* iconfont的网站生成 */
    @import 'http://at.alicdn.com/t/c/font_3660333_clz5n3z0jtw.css';
  
    .tab-bar-item {
      flex: 1;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
  
      font-size: 12px;
      color: white;
    }
    .tab-bar-item i {
      font-size: 18px;
    }
    .tab-bar-item.active {
      color: red;
    }
  </style>